Page({
  data: {
    currentSong: null,
    isPlaying: false,
    progress: 0,
    currentTime: '00:00',
    duration: '00:00',
    isFavorite: false,
    playMode: 'list', // list: 列表循环, loop: 单曲循环, random: 随机播放
    currentPlaylist: []
  },
  onLoad(options) {
    const app = getApp()
    
    // 如果通过URL参数传递歌曲信息，则使用这些信息
    if (options.musicId) {
      const song = {
        id: options.musicId,
        name: decodeURIComponent(options.name || ''),
        artist: decodeURIComponent(options.artist || ''),
        cover: decodeURIComponent(options.cover || ''),
        url: decodeURIComponent(options.url || ''),
        picUrl: decodeURIComponent(options.cover || ''),
        duration: decodeURIComponent(options.duration || '')
      }
      
      app.globalData.currentSong = song
      this.addToPlayHistory(song)
    }
    
    // 获取当前播放列表
    const currentPlaylist = app.globalData.currentPlaylist || []
    
    this.setData({
      currentSong: app.globalData.currentSong,
      isPlaying: app.globalData.isPlaying,
      isFavorite: app.isFavorite(app.globalData.currentSong?.id),
      // 初始化时长显示
      duration: app.globalData.currentSong?.duration || '00:00',
      currentPlaylist: currentPlaylist,
      playMode: app.globalData.playMode || 'list'
    })
    
    // 监听音频事件
    app.globalData.audioManager.onTimeUpdate(() => {
      this.updateProgress()
    })
    
    app.globalData.audioManager.onPlay(() => {
      this.setData({ isPlaying: true })
      app.globalData.isPlaying = true
      
      // 记录播放历史
      if (this.data.currentSong) {
        this.addToPlayHistory(this.data.currentSong)
      }
    })
    
    app.globalData.audioManager.onPause(() => {
      this.setData({ isPlaying: false })
      app.globalData.isPlaying = false
    })
    
    app.globalData.audioManager.onEnded(() => {
      const playMode = this.data.playMode
      
      if (playMode === 'loop') {
        // 单曲循环，重新播放当前歌曲
        const app = getApp()
        app.globalData.audioManager.seek(0)
        app.globalData.audioManager.play()
      } else {
        // 列表循环或随机播放，播放下一首
        this.next()
      }
    })
  },
  updateProgress() {
    const audio = getApp().globalData.audioManager
    const currentSong = this.data.currentSong
    
    // 优先使用歌曲数据中的时长，如果音频管理器没有时长或为0
    const totalDuration = currentSong && currentSong.duration ? 
      this.parseDuration(currentSong.duration) : 
      (audio.duration || 0)
    
    this.setData({
      progress: (audio.currentTime / totalDuration) * 100 || 0,
      currentTime: this.formatTime(audio.currentTime),
      duration: currentSong && currentSong.duration ? currentSong.duration : this.formatTime(totalDuration)
    })
  },
  formatTime(seconds) {
    if (!seconds || seconds <= 0) return '00:00'
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  },
  
  // 将字符串时长（如"3:43"）转换为秒数
  parseDuration(durationStr) {
    if (!durationStr) return 0
    const parts = durationStr.split(':')
    if (parts.length === 2) {
      return parseInt(parts[0]) * 60 + parseInt(parts[1])
    }
    return 0
  },
  togglePlay() {
    const app = getApp()
    if (app.globalData.isPlaying) {
      app.globalData.audioManager.pause()
    } else {
      app.globalData.audioManager.play()
    }
    this.setData({ isPlaying: !this.data.isPlaying })
  },
  // 设置播放模式
  setPlayMode(e) {
    const mode = e.currentTarget.dataset.mode
    const app = getApp()
    
    this.setData({
      playMode: mode
    })
    
    app.globalData.playMode = mode
    
    // 显示模式提示
    const modeText = {
      'list': '列表循环',
      'loop': '单曲循环', 
      'random': '随机播放'
    }
    
    wx.showToast({
      title: modeText[mode],
      icon: 'none',
      duration: 1000
    })
  },
  
  prev() {
    const app = getApp()
    const currentIndex = app.globalData.currentSongIndex
    const playlist = this.data.currentPlaylist
    const playMode = this.data.playMode
    
    if (playlist && playlist.length > 0) {
      let prevIndex
      
      switch (playMode) {
        case 'loop': // 单曲循环，播放当前歌曲
          prevIndex = currentIndex
          break
        case 'random': // 随机播放
          prevIndex = Math.floor(Math.random() * playlist.length)
          break
        default: // 列表循环
          prevIndex = currentIndex > 0 ? currentIndex - 1 : playlist.length - 1
      }
      
      const prevSong = playlist[prevIndex]
      
      app.globalData.currentSong = prevSong
      app.globalData.currentSongIndex = prevIndex
      
      this.setData({
        currentSong: prevSong
      })
      
      // 静默播放，不显示错误提示
      this.silentPlaySong(prevSong)
    }
  },
  next() {
    const app = getApp()
    const currentIndex = app.globalData.currentSongIndex
    const playlist = this.data.currentPlaylist
    const playMode = this.data.playMode
    
    if (playlist && playlist.length > 0) {
      let nextIndex
      
      switch (playMode) {
        case 'loop': // 单曲循环，播放当前歌曲
          nextIndex = currentIndex
          break
        case 'random': // 随机播放
          nextIndex = Math.floor(Math.random() * playlist.length)
          break
        default: // 列表循环
          nextIndex = currentIndex < playlist.length - 1 ? currentIndex + 1 : 0
      }
      
      const nextSong = playlist[nextIndex]
      
      app.globalData.currentSong = nextSong
      app.globalData.currentSongIndex = nextIndex
      
      this.setData({
        currentSong: nextSong
      })
      
      // 静默播放，不显示错误提示
      this.silentPlaySong(nextSong)
    }
  },
  onProgressChange(e) {
    const app = getApp()
    const audioManager = app.globalData.audioManager
    if (audioManager.duration) {
      const newTime = (e.detail.value / 100) * audioManager.duration
      audioManager.seek(newTime)
    }
  },

  // 添加到播放历史
  addToPlayHistory(song) {
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      return // 未登录用户不记录历史
    }

    const app = getApp()
    app.addToHistory(song)
  },

  // 切换收藏状态
  toggleFavorite() {
    const app = getApp()
    const currentSong = this.data.currentSong
    
    if (!currentSong) {
      wx.showToast({
        title: '当前没有播放歌曲',
        icon: 'none'
      })
      return
    }
    
    // 检查是否已登录
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    const isFavorite = app.isFavorite(currentSong.id)
    
    if (isFavorite) {
      // 取消收藏
      app.removeFromFavorites(currentSong.id)
      this.setData({
        isFavorite: false
      })
    } else {
      // 添加收藏
      const success = app.addToFavorites(currentSong)
      if (success) {
        this.setData({
          isFavorite: true
        })
      }
    }
  },

  // 静默播放歌曲，不显示错误提示
  silentPlaySong(song) {
    const app = getApp()
    if (!song) return
    
    try {
      app.globalData.currentSong = song
      app.globalData.audioManager.title = song.name
      app.globalData.audioManager.singer = song.artist
      app.globalData.audioManager.coverImgUrl = song.picUrl || song.cover || '/assets/default-cover.svg'
      
      // 使用歌曲的URL，如果没有则尝试从API获取
      if (song.url) {
        app.globalData.audioManager.src = song.url
      } else {
        // 尝试从API获取播放URL
        app.getSongUrl(song.id).then(url => {
          app.globalData.audioManager.src = url
        }).catch(error => {
          console.error('获取播放URL失败:', error)
          // 使用默认URL
          app.globalData.audioManager.src = '/assets/audio/default.mp3'
        })
      }
      
      app.globalData.isPlaying = true
      
      // 播放时添加到历史记录
      this.addToPlayHistory(song)
      
    } catch (error) {
      console.error('播放歌曲失败:', error)
      // 静默失败，不显示错误提示
    }
  },

  onShow() {
    // 更新收藏状态
    const app = getApp()
    if (this.data.currentSong) {
      this.setData({
        isFavorite: app.isFavorite(this.data.currentSong.id)
      })
    }
  }
})